﻿using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Windows.Forms;
using Microsoft.WowAddonStudio.FrameXml.Components.Support;

namespace Microsoft.WowAddonStudio.FrameXml.Components.Tests
{
	public class ReflectionComponentActivator : IComponentActivator
	{
		private readonly INameCreationService nameCreationService;
		private readonly IContainer container;

		/// <summary>
		/// Initializes a new instance of the <see cref="ReflectionComponentActivator"/> class.
		/// </summary>
		public ReflectionComponentActivator()
		{
			nameCreationService = new TestNameCreationService();
			container = new TestComponentContainer();
		}

		/// <summary>
		/// Creates a component.
		/// </summary>
		/// <param name="componentClass">The type of the component.</param>
		/// <returns>The newly created component.</returns>
		public object CreateComponent(Type componentClass)
		{
			if (componentClass == null)
				throw new ArgumentNullException("componentClass");

			object instance = Activator.CreateInstance(componentClass);
			Component ctrl = instance as Control ?? instance as Component;

			if (ctrl != null)
			{
				string generatedName = nameCreationService.CreateName(container, ctrl.GetType());
				if (ctrl.Site != null) ctrl.Site.Name = generatedName;
				if (ctrl is Control) ((Control) ctrl).Name = generatedName;
			}

			container.Add(ctrl);

			return instance;
		}
	}
}